package net.dotool.resource;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

import net.dotool.Charsets;
import net.dotool.DoToolException;
import net.dotool.IoTools;
import net.dotool.URLTools;

/**
 * URL资源访问类
 *
 */
public class UrlResource implements Resource {

	protected URL url;
	protected String name;

	// --------------------------------------------------------------------------------------
	// Constructor start
	/**
	 * 构造
	 * 
	 * @param url
	 *            URL
	 */
	public UrlResource(URL url) {
		this(url, null);
	}

	/**
	 * 构造
	 * 
	 * @param url
	 *            URL
	 * @param name
	 *            资源名称
	 */
	public UrlResource(URL url, String name) {
		this.url = url;
		this.name = name;
	}

	/**
	 * 构造
	 * 
	 * @param file
	 *            文件路径
	 * @deprecated Please use {@link FileResource}
	 */
	@Deprecated
	public UrlResource(File file) {
		this.url = URLTools.getURL(file);
	}
	// --------------------------------------------------------------------------------------
	// Constructor end

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public URL getUrl() {
		return this.url;
	}

	@Override
	public InputStream getStream() {
		if (null == this.url) {
			throw new DoToolException("Resource [{}] not exist!", this.url);
		}
		return URLTools.getStream(url);
	}

	/**
	 * 获得Reader
	 * 
	 * @param charset
	 *            编码
	 * @return {@link BufferedReader}
	 * @since 3.0.1
	 */
	public BufferedReader getReader(Charset charset) {
		return URLTools.getReader(this.url, charset);
	}

	// -------------------------------------------------------------------------------
	// read
	@Override
	public String readStr(Charset charset) throws DoToolException {
		BufferedReader reader = null;
		try {
			reader = getReader(charset);
			return IoTools.read(reader);
		} finally {
			IoTools.closeIos(reader);
		}
	}

	@Override
	public String readUtf8Str() throws DoToolException {
		return readStr(Charsets.UTF_8);
	}

	@Override
	public byte[] readBytes() throws DoToolException {
		InputStream in = null;
		try {
			in = getStream();
			return IoTools.readBytes(in);
		} finally {
			IoTools.closeIos(in);
		}
	}

	/**
	 * 获得File
	 * 
	 * @return {@link File}
	 */
	public File getFile() {
		try {
			return new File(this.url.toURI());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 返回路径
	 * 
	 * @return 返回URL路径
	 */
	@Override
	public String toString() {
		return (null == this.url) ? "null" : this.url.toString();
	}
}
